// 994.腐烂的橘子
package LeetcodeHot100;

import java.util.Deque;
import java.util.LinkedList;

public class Solution994 {
    public int orangesRotting(int[][] grid) {
        // 利用队列实现广度优先遍历，队列中的元素表示当前时刻腐烂的橘子
        Deque<int[]> queue = new LinkedList<>();
        // 遍历图，将初始腐烂的橘子加入队列
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] != 2)
                    continue;
                queue.offer(new int[] { i, j });
            }
        }

        int time = 0; // 初始时间为 0
        while (!queue.isEmpty()) {
            int size = queue.size(); // 当前时间点腐烂橘子的个数
            // 遍历当前时刻每个腐烂的橘子
            while (size-- != 0) {
                int[] poll = queue.poll();
                // 当前腐烂橘子扩散腐烂到四周
                if (poll[0] + 1 < grid.length && grid[poll[0] + 1][poll[1]] == 1) {
                    grid[poll[0] + 1][poll[1]] = 2;
                    queue.offer(new int[] { poll[0] + 1, poll[1] });
                }
                if (poll[0] - 1 >= 0 && grid[poll[0] - 1][poll[1]] == 1) {
                    grid[poll[0] - 1][poll[1]] = 2;
                    queue.offer(new int[] { poll[0] - 1, poll[1] });
                }
                if (poll[1] + 1 < grid[0].length && grid[poll[0]][poll[1] + 1] == 1) {
                    grid[poll[0]][poll[1] + 1] = 2;
                    queue.offer(new int[] { poll[0], poll[1] + 1 });
                }
                if (poll[1] - 1 >= 0 && grid[poll[0]][poll[1] - 1] == 1) {
                    grid[poll[0]][poll[1] - 1] = 2;
                    queue.offer(new int[] { poll[0], poll[1] - 1 });
                }
            }
            // 如果当前有新的腐烂橘子，则time++继续传播，否则表示当前已腐烂完成
            if (!queue.isEmpty())
                time++;
        }

        // 当图中有非联通的情况，则返回 -1
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    return -1;
                }
            }
        }

        // 返回最终结果
        return time;
    }
}
